<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 优惠券码搜索字段已删除 -->
      <el-form-item label="优惠券" prop="couponId">
        <id-selector
          v-model="queryParams.couponId"
          placeholder="请选择优惠券"
          dialog-title="选择优惠券"
          :api-function="listConponList"
          :get-api-function="getConponList"
          id-field="couponId"
          name-field="couponName"
          id-label="优惠券ID"
          name-label="优惠券名称"
          search-label="优惠券名称"
          search-placeholder="请输入优惠券名称"
          :extra-columns="[{prop: 'couponType', label: '优惠券类型'}, {prop: 'couponAmount', label: '优惠金额'}]"
          :extra-params="{orgId: currentOrgId}"
        />
      </el-form-item>
      <el-form-item label="用户" prop="userId">
        <id-selector
          v-model="queryParams.userId"
          placeholder="请选择用户"
          dialog-title="选择用户"
          :api-function="listUser"
          :get-api-function="getUser"
          id-field="userId"
          name-field="userName"
          id-label="用户ID"
          name-label="用户名称"
          search-label="用户名称"
          search-placeholder="请输入用户名称"
          :extra-columns="[{prop: 'nickName', label: '用户昵称'}, {prop: 'email', label: '邮箱'}]"
          :extra-params="{deptId: currentDeptId}"
        />
      </el-form-item>
      <el-form-item label="使用状态" prop="useStatus">
        <el-select v-model="queryParams.useStatus" placeholder="请选择使用状态" clearable>
          <el-option
            v-for="dict in dict.type.ec_use_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="使用时间" prop="usedTime">
        <el-date-picker clearable
          v-model="queryParams.usedTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择使用时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="使用订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入使用订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="获取类型" prop="getType">
        <el-select v-model="queryParams.getType" placeholder="请选择获取类型" clearable>
          <el-option
            v-for="dict in dict.type.ec_get_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="优惠券码" prop="couponCode">
        <el-input
          v-model="queryParams.couponCode"
          placeholder="请输入优惠券码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleGrant"
          v-hasPermi="['fun:conponList:add']"
        >发放优惠券</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fun:conponList:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fun:conponList:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleVerify"
          v-hasPermi="['fun:conponList:verify']"
        >核验优惠券</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户优惠券ID" align="center" prop="userCouponId" />
      <!-- 创建组织列已隐藏 -->
      <el-table-column label="优惠券名称" align="center" prop="couponId">
        <template slot-scope="scope">
          <span>{{ getCouponName(scope.row.couponId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名称" align="center" prop="userId">
        <template slot-scope="scope">
          <span>{{ getUserName(scope.row.userId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠券码" align="center" prop="couponCode" />
      <!-- 优惠券码列已删除 -->
      <el-table-column label="使用状态" align="center" prop="useStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ec_use_status" :value="scope.row.useStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="使用时间" align="center" prop="usedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.usedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用订单号" align="center" prop="orderNo" />
      <el-table-column label="获取类型" align="center" prop="getType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ec_get_type" :value="scope.row.getType"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fun:conponList:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 发放优惠券对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="优惠券" prop="couponId">
          <id-selector
            v-model="form.couponId"
            placeholder="请选择优惠券"
            dialog-title="选择优惠券"
            :api-function="listConponList"
            :get-api-function="getConponList"
            id-field="couponId"
            name-field="couponName"
            id-label="优惠券ID"
            name-label="优惠券名称"
            search-label="优惠券名称"
            search-placeholder="请输入优惠券名称"
            :extra-columns="[{prop: 'couponType', label: '优惠券类型'}, {prop: 'couponAmount', label: '优惠金额'}]"
            :extra-params="{orgId: currentOrgId}"
          />
        </el-form-item>
        <el-form-item label="用户" prop="userId">
          <id-selector
            v-model="form.userId"
            placeholder="请选择用户"
            dialog-title="选择用户"
            :api-function="listUser"
            :get-api-function="getUser"
            id-field="userId"
            name-field="userName"
            id-label="用户ID"
            name-label="用户名称"
            search-label="用户名称"
            search-placeholder="请输入用户名称"
            :extra-columns="[{prop: 'nickName', label: '用户昵称'}, {prop: 'email', label: '邮箱'}]"
            :extra-params="{deptId: currentDeptId}"
          />
        </el-form-item>
        <!-- 优惠券码和使用状态字段已删除，使用状态由代码自动设置为未使用 -->
        <!-- 使用时间和使用订单号字段已隐藏，由代码自动填写 -->
        <el-form-item label="获取类型" prop="getType">
          <el-select v-model="form.getType" placeholder="请选择获取类型">
            <el-option
              v-for="dict in dict.type.ec_get_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 核验优惠券对话框 -->
    <el-dialog title="核验优惠券" :visible.sync="verifyOpen" width="500px" append-to-body>
      <el-form ref="verifyForm" :model="verifyForm" :rules="verifyRules" label-width="120px">
        <el-form-item label="优惠券验证码" prop="verifyCode">
          <el-input
            v-model="verifyForm.verifyCode"
            placeholder="请输入格式：优惠券码_用户优惠券ID"
            clearable
          />
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            格式说明：优惠券码_用户优惠券ID（例如：ABC123_456）
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitVerify">确 定</el-button>
        <el-button @click="cancelVerify">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUserCoupon, getUserCoupon, delUserCoupon, addUserCoupon, updateUserCoupon, verifyCoupon } from "@/api/fun/userCoupon";
import { listConponList, getConponList } from "@/api/fun/conponList";
import { listUser, getUser } from "@/api/system/user";
import CacheManager from '@/utils/cacheManager'
import IdSelector from '@/components/IdSelector';

import { getDept } from "@/api/system/dept"
export default {
  name: "UserCoupon",
  dicts: ['ec_use_status', 'ec_get_type'],
  components: {
    IdSelector
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户优惠券表格数据
      couponList: [],
      // 当前用户的组织ID和部门ID
      currentOrgId: null,
      currentDeptId: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示核验弹出层
      verifyOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        couponId: null,
        userId: null,
        couponCode: null,
        useStatus: null,
        usedTime: null,
        orderNo: null,
        getType: null,
      },
      // API方法
      listConponList,
      getConponList,
      listUser,
      getUser,
      // 表单参数
      form: {},
      // 核验表单参数
      verifyForm: {
        verifyCode: ''
      },
      // 表单校验
      rules: {
        couponId: [
          { required: true, message: "优惠券不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "用户不能为空", trigger: "blur" }
        ],
        getType: [
          { required: true, message: "获取类型不能为空", trigger: "change" }
        ]
      },
      // 核验表单校验
      verifyRules: {
        verifyCode: [
          { required: true, message: "优惠券验证码不能为空", trigger: "blur" },
          {
            pattern: /^.+_.+$/,
            message: "请输入正确格式：优惠券码_用户优惠券ID",
            trigger: "blur"
          }
        ]
      }
    }
  },
  created() {
    // 初始化当前用户的组织ID和部门ID
    this.currentOrgId = this.$store.getters.orgId || (this.$store.getters.user && this.$store.getters.user.deptId)
    this.currentDeptId = this.$store.getters.user && this.$store.getters.user.deptId
    this.getList()
  },
  mounted() {
    // 监听表单提交事件
    this.$eventBus.$on('refreshCouponList', () => {
      this.getList()
    })
  },
  beforeDestroy() {
    // 移除事件监听器
    this.$eventBus.$off('refreshCouponList')
  },
  methods: {
    /** 根据优惠券ID获取优惠券名称 */
    getCouponName(couponId) {
      return CacheManager.getCouponName(couponId, getConponList)
    },
    /** 根据用户ID获取用户名称 */
    getUserName(userId) {
      return CacheManager.getUserName(userId, getUser)
    },
    /** 查询用户优惠券列表 */
    getList() {
      this.loading = true
      listUserCoupon(this.queryParams).then(response => {
        this.couponList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        couponId: null,
        userId: null,
        getType: null,
        useStatus: 0 // 默认未使用
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userCouponId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 发放优惠券按钮操作 */
    handleGrant() {
      this.reset()
      this.open = true
      this.title = "发放优惠券"
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 设置使用状态为未使用(0)
          this.form.useStatus = 0
          addUserCoupon(this.form).then(response => {
            this.$modal.msgSuccess("发放成功")
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 核验优惠券按钮操作 */
    handleVerify() {
      this.verifyForm.verifyCode = ''
      this.verifyOpen = true
    },
    /** 提交核验 */
     submitVerify() {
       this.$refs["verifyForm"].validate(valid => {
         if (valid) {
           // 调用后端核验接口
           verifyCoupon({ verifyCode: this.verifyForm.verifyCode }).then(response => {
             // 检查返回的success标志位
             if (response.success === 1) {
               this.$modal.msgSuccess(response.msg || "优惠券核验成功")
               this.verifyOpen = false
               this.getList() // 刷新列表
             } else {
               // 核验失败，显示红色错误提示
               this.$modal.msgError(response.msg || "核验失败")
             }
           }).catch(error => {
             this.$modal.msgError("系统错误：" + (error.msg || "请稍后重试"))
           })
         }
       })
     },
    /** 取消核验 */
    cancelVerify() {
      this.verifyOpen = false
      this.verifyForm.verifyCode = ''
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userCouponIds = row.userCouponId || this.ids
      this.$modal.confirm('是否确认删除用户优惠券编号为"' + userCouponIds + '"的数据项？').then(function() {
        return delUserCoupon(userCouponIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fun/userCoupon/export', {
        ...this.queryParams
      }, `userCoupon_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
